import { config } from './config.js';

class Dashboard {
    constructor() {
        this.init();
        this.checkAuth();
        this.bindEvents();
        this.loadStats();
        this.initTheme();
    }

    init() {
        // 获取DOM元素
        this.userEmail = document.getElementById('userEmail');
        this.bioAuthStatus = document.getElementById('bioAuthStatus');
        this.passwordCount = document.getElementById('passwordCount');
        this.noteCount = document.getElementById('noteCount');
        this.logoutBtn = document.getElementById('logoutBtn');
        this.toggleBioAuthBtn = document.getElementById('toggleBioAuth');
        this.themeToggleBtn = document.getElementById('themeToggle');
    }

    checkAuth() {
        // 检查是否已登录
        const token = localStorage.getItem('token');
        if (!token) {
            window.location.href = '/index.html';
            return;
        }

        // 解析token中的邮箱（实际应用中应该从后端获取用户信息）
        try {
            const payload = JSON.parse(atob(token.split('.')[1]));
            this.userEmail.textContent = payload.email;
        } catch (error) {
            console.error('Token解析失败:', error);
            this.logout();
        }
    }

    initTheme() {
        // 从本地存储加载主题设置
        const savedTheme = localStorage.getItem('theme') || 'dark';
        document.documentElement.setAttribute('data-theme', savedTheme);
        this.updateThemeIcon(savedTheme);
    }

    updateThemeIcon(theme) {
        const icon = this.themeToggleBtn.querySelector('.icon');
        icon.textContent = theme === 'dark' ? '🌓' : '🌞';
    }

    toggleTheme() {
        const currentTheme = document.documentElement.getAttribute('data-theme');
        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
        
        // 更新 DOM
        document.documentElement.setAttribute('data-theme', newTheme);
        
        // 更新图标
        this.updateThemeIcon(newTheme);
        
        // 保存到本地存储
        localStorage.setItem('theme', newTheme);
    }

    bindEvents() {
        // 退出登录
        this.logoutBtn.addEventListener('click', () => this.logout());

        // 主题切换
        this.themeToggleBtn.addEventListener('click', () => this.toggleTheme());

        // 功能卡片点击事件
        document.getElementById('passwordManager').addEventListener('click', () => {
            window.location.href = 'passwords.html';
        });

        document.getElementById('notepad').addEventListener('click', () => {
            window.location.href = 'notes.html';
        });

        // 生物认证开关
        this.toggleBioAuthBtn.addEventListener('click', () => this.toggleBioAuth());
    }

    async loadStats() {
        try {
            // 获取密码数量
            const response = await fetch(`${config.API_BASE_URL}/api/passwords/count`, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });

            if (!response.ok) {
                throw new Error('获取统计信息失败');
            }

            const result = await response.json();
            if (result.ok) {
                this.passwordCount.textContent = result.data.count;
            }

        } catch (error) {
            console.error('加载统计信息失败:', error);
            // 不显示错误提示，保持默认值0
        }
    }

    async toggleBioAuth() {
        // 检查浏览器是否支持生物认证
        if (!window.PublicKeyCredential) {
            alert('您的浏览器不支持生物认证');
            return;
        }

        try {
            // 这里添加生物认证的具体实现
            alert('生物认证功能正在开发中');
        } catch (error) {
            console.error('生物认证操作失败:', error);
            alert('生物认证操作失败');
        }
    }

    logout() {
        localStorage.clear();
        window.location.href = 'index.html';
    }
}

// 初始化仪表板
document.addEventListener('DOMContentLoaded', () => {
    new Dashboard();
}); 